package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.common.exception.CustomException;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description:
 * @Version: V1.0
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {
    /**
     * 登录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(AdUserDto dto) {
        //1 参数校验
        if (dto == null || StringUtils.isBlank(dto.getName()) || StringUtils.isBlank(dto.getPassword())) {
            throw new CustomException(AppHttpCodeEnum.ADUSER_VALID_ERROR);
        }
        //2 根据当前登录用户查询用户信息
        AdUser adUser = getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, dto.getName()));
        if (adUser == null) {
            throw new CustomException(AppHttpCodeEnum.ADUSER_NOTEXIST_ERROR);
        }

        //3 比对密码
        // 获取数据库密码
        String dbPwd = adUser.getPassword();
        // 用户输入密码
        String password = dto.getPassword();
        String salt = adUser.getSalt();
        String pwd = DigestUtils.md5DigestAsHex((password + salt).getBytes());
        if (!dbPwd.equals(pwd)) {
            throw new CustomException(AppHttpCodeEnum.ADUSER_NAMEORPWD_ERROR);
        }

        //4 成功则生成jwt令牌，封装返回结果
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("token", AppJwtUtil.getToken(adUser.getId().longValue()));
        adUser.setPassword(null);
        adUser.setSalt(null);
        resultMap.put("user", adUser);

        //5 更新用户登录时间
        adUser.setLoginTime(new Date());
        updateById(adUser);

        return ResponseResult.okResult(resultMap);
    }
}
